import { Component, EventEmitter, OnInit, Output, ViewChild } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { Router } from '@angular/router';
import { UserAuthService } from '@core/services/user-auth.service';
import { GridConfigService } from '@core/config/grid-config.service';
import { DatePipe } from '@angular/common';
import { ApesMessageService } from '@shared/apes/message';
import { CarDetailsComponent } from '../car-info/car-details/car-details.component';
import { GridOptions } from '@ag-grid-community/core';

@Component({
  selector: 'dome-index',
  templateUrl: './dome-index.component.html',
  styleUrls: ['./dome-index.component.scss'],
})
export class DomeIndexComponent implements OnInit {

  /** Grid 相关 **/
  rowData: any[] = [];
  resultData: any;
  gridOptions: GridOptions;
  pinnedBottomRowData: any[] = [];
  columnDefs: any[] = [];
  rowClassRules: any;
  height: any = window.innerHeight - 230 + 'px';

  ngJD: any;
  posts: any;                // 获取登录角色所在门店ID
  queryList: any[];
  query: any;

  @Output() loadStates = new EventEmitter<any>();

  constructor(private apiService: ApiService,
              public gridConfigService: GridConfigService,
              public userAuthService: UserAuthService,
              public router: Router, private msg: ApesMessageService) {

    const userInfo = this.userAuthService.getUserInfoObj();
    if(userInfo.userAccount.post.dept !== undefined) {
      this.posts = userInfo.userAccount.post.dept.id;
    }else {
      this.posts = null;
    }
    this.columnDefs = [
      { 'headerName': '车牌', field: 'CPHM', width: 85, pinned: 'left' },
      { 'headerName': '接车人', field: 'JIECRMC', width: 80 },
      { 'headerName': '接车时间', field: 'JCRQ_SJ', width: 120 },
      { 'headerName': '预计交车时间', field: 'YJJCRQ_SJ', width: 120 },
      { 'headerName': '当前节点', field: 'JD', width: 100 },
      { 'headerName': '项目', field: 'FWLXMC', width: 100 },
      { 'headerName': '定损', field: 'DSBJ', width: 65 },
      { 'headerName': '节点耗时', field: 'JDHS', width: 110, cellRenderer: this.toHour },
      { 'headerName': '节点超时', field: 'JDCS', width: 110, cellRenderer: this.toHour },
      { 'headerName': '总耗时', field: 'HJCS', width: 110, cellRenderer: this.toHour },
      { 'headerName': '厂牌', field: 'QCCPMC', width: 110 },
      { 'headerName': '车型', field: 'CHXMC', width: 110 },

    ];

    // 初始化 grid
    this.gridOptions = <GridOptions>{
      toolPanelSuppressSideButtons: true,
      suppressExcelExport: true,
      suppressCsvExport: true,
      suppressSizeToFit: true,
      showToolPanel: false,
      pagination: true,
      paginationPageSize: 50,
      rowHeight: 35,
    };
    this.gridOptions.localeText = gridConfigService.getLocaleText();
    this.rowClassRules = {
      // 预警
      'grid-tab-breach': function(params) {
        let YJJCSJ = params.data.YJJCRQ;
        let now = params.data.YJCS;
        let overTime = params.data.JDCS;
        if (now > 0 && overTime <= 0) {
          return (now > 0 && overTime <= 0);
        } else {
          return (YJJCSJ > -60 && YJJCSJ <= 0);
        }
      },
      // 超时
      'grid-tab-warning': function(params) {
        let YJJCSJ = params.data.YJJCRQ;
        let overTime = params.data.JDCS;
        if (overTime > 0) {
          return overTime > 0;
        } else {
          return YJJCSJ > 0;
        }
      },
    };
  }

  ngOnInit() {
    this.getTablesData();
    this.getQueryHead();
  }

  btnChange(key: any) {
    this.query = key;
  }

  ngAfterViewInit() {
    this.loadStates.emit(true);
  }

  /**
   * 功能：按钮事件路由
   * @param data 当前按钮元数据
   */
  onEvent() {
    this.rowData = [];
    this.getTablesData();
  }

//  注销按钮
  loadTwo() {
    this.userAuthService.removeUserInfo();
    this.router.navigateByUrl('/passport');
  }

  getTablesData() {
    let data = {
      'interfaceMethod': 'ipmCLZKForAppService.getLeftTotal', 'pdata': {
        'JD': this.ngJD, 'MDID': this.posts, 'KEY': 'CARINSTORE',
      },
    };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            let nowDate = new Date().getTime();
            for (let i = 0, len = data.length; i < len; i++) {
              if (data[i]['DSBJ'] === 1) {
                data[i]['DSBJ'] = '√';
              } else {
                data[i]['DSBJ'] = null;
              }
              if (data[i]['JDCS'] < 0) {
                data[i]['JDCS'] = null;
              }
              if (data[i]['YJJCRQ_SJ'] !== undefined) {
                data[i]['YJJCRQ'] = parseInt(((nowDate - new Date(data[i]['YJJCRQ_SJ']).getTime()) / 1000 / 60).toFixed());
              }
              data[i]['YJJCRQ_SJ'] = this.timesMDHMS(data[i]['YJJCRQ_SJ']);
              data[i]['JCRQ_SJ'] = this.timesMDHMS(data[i]['JCRQ_SJ']);
            }
            this.rowData = data;
            if (this.rowData.length === 0) {
              this.msg.info(`未找到满足条件的数据`);
            }
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }

// 获取 查询头部
  getQueryHead() {
    let data = { 'interfaceMethod': 'ipmCLZKForAppService.getClzkHead', 'pdata': { 'MDID': this.posts } };
    this.apiService.post('report.interface', { 'body': JSON.stringify(data) }).subscribe(
      (resultData) => {
        const result = JSON.parse(resultData);
        if (result.success) {
          if (result.obj.length !== 0) {
            let data = JSON.parse(result.obj);
            this.queryList = data;
          }
        } else {
          this.msg.info(result.msg);
        }
      });
  }


// 时间转换（配合grid调用）
  toHour(params) {
    let key = params.colDef.field;
    let data = params.data[key];

    let day = Math.floor(data / 1440);
    let hour = day >= 0
      ? Math.floor((data - (day * 1440)) / 60)
      : Math.floor(data / 60);
    let minute = hour >= 0
      ? Math.floor(data - (day * 1440) - (hour * 60))
      : Math.floor(data / 60 / 24);

    let time = '';
    if (day > 0) {
      // time = day + "天" + hour + "小时";
      time = day + '天' + hour + '小时' + minute + '分钟';
    } else if (hour > 0) {
      time = hour + '小时' + minute + '分钟';
    } else if (minute > 0) {
      time = minute + '分钟';
    }
    return time;
  }

// 截取 月、日、时、分、秒
  timesMDHMS(key: string) {
    if (key !== undefined) {
      key = key.slice(5, 19);
    }
    return key;
  }

}
